document.addEventListener('DOMContentLoaded', function() {
  // DOM元素引用
  const addButton = document.getElementById('add-button');
  const titleInput = document.getElementById('bookmark-title');
  const urlInput = document.getElementById('bookmark-url');
  const tagsInput = document.getElementById('bookmark-tags');
  const bookmarkGrid = document.getElementById('bookmarks-container');
  const editModal = document.getElementById('edit-modal');
  const closeEditModal = document.querySelector('.close-btn');
  const saveEditButton = document.getElementById('save-edit-btn');
  const cancelEditButton = document.getElementById('cancel-edit-btn');
  const editTitleInput = document.getElementById('edit-title');
  const editUrlInput = document.getElementById('edit-url');
  const editTagsInput = document.getElementById('edit-tags');
  const searchInput = document.getElementById('search-input');
  const searchButton = document.getElementById('search-button');
  const sortSelect = document.getElementById('sort-select');
  const currentTagName = document.getElementById('current-tag-name');
  const addTagButton = document.getElementById('add-tag-btn');
  const tagList = document.querySelector('.tag-list');
  const exportButton = document.getElementById('export-btn');
  const importButton = document.getElementById('import-btn');
  const importInput = document.getElementById('import-file');

  // 全局变量
  let bookmarks = [];
  let tags = [];
  let currentTag = 'all';
  let searchQuery = '';
  let editingBookmarkId = null;
  let selectedBookmarks = new Set();

  // 初始化函数
  function init() {
    loadData();
    renderTags();
    renderBookmarks();
    setupEventListeners();
  }

  // 加载数据
  function loadData() {
    // 加载书签
    const storedBookmarks = localStorage.getItem('bookmarks');
    if (storedBookmarks) {
      bookmarks = JSON.parse(storedBookmarks);
    } else {
      // 初始化为空数组，不生成示例书签
      bookmarks = [];
      saveBookmarks();
    }

    // 从书签中提取所有标签
    extractTags();
  }

  // 从书签中提取所有标签
  function extractTags() {
    const allTags = new Set();
    bookmarks.forEach(bookmark => {
      bookmark.tags.forEach(tag => {
        allTags.add(tag);
      });
    });
    tags = Array.from(allTags).sort();
  }

  // 保存书签数据到本地存储
  function saveBookmarks() {
    localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
  }

  // 设置事件监听器
  function setupEventListeners() {
    // 添加新书签
    addButton.addEventListener('click', handleAddBookmark);

    // 编辑和删除书签事件委托
    bookmarkGrid.addEventListener('click', handleBookmarkAction);

    // 编辑模态框事件
    closeEditModal.addEventListener('click', closeModal);
    cancelEditButton.addEventListener('click', closeModal);
    saveEditButton.addEventListener('click', handleSaveEdit);

    // 搜索事件
    searchButton.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        handleSearch();
      }
    });
    
    // 自动搜索（输入时实时搜索）
    searchInput.addEventListener('input', debounce(function() {
      handleSearch();
    }, 300));
    
    // 批量操作元素
    const batchActions = document.querySelector('.batch-actions');
    const selectedCount = document.getElementById('selected-count');
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    const cancelSelectionBtn = document.getElementById('cancel-selection-btn');
    
    // 批量选择相关变量
    let selectedBookmarks = new Set();
    
    // 批量删除事件
    batchDeleteBtn.addEventListener('click', handleBatchDelete);
    cancelSelectionBtn.addEventListener('click', cancelSelection);
    
    // 添加快捷键支持
    document.addEventListener('keydown', handleKeyPress);
    
    // 添加标签右键菜单功能
    setupTagContextMenu();

    // 排序事件
    sortSelect.addEventListener('change', renderBookmarks);

    // 标签选择事件委托
    tagList.addEventListener('click', handleTagClick);

    // 添加标签
    addTagButton.addEventListener('click', handleAddTag);

    // 导入导出
    exportButton.addEventListener('click', handleExport);
    importButton.addEventListener('click', () => importInput.click());
    importInput.addEventListener('change', handleImport);

    // 点击模态框外部关闭模态框
    editModal.addEventListener('click', function(e) {
      if (e.target === editModal) {
        closeModal();
      }
    });
  }

  // 渲染标签列表
  function renderTags() {
    tagList.innerHTML = '';

    // 添加"全部"标签
    const allTagItem = document.createElement('div');
    allTagItem.classList.add('tag-item');
    if (currentTag === 'all') {
      allTagItem.classList.add('active');
    }
    allTagItem.dataset.tag = 'all';
    allTagItem.innerHTML = `
      <span>全部书签</span>
      <span class="tag-count">${bookmarks.length}</span>
    `;
    tagList.appendChild(allTagItem);

    // 添加所有其他标签
    tags.forEach(tag => {
      const tagCount = bookmarks.filter(bookmark => 
        bookmark.tags.includes(tag)
      ).length;

      const tagItem = document.createElement('div');
      tagItem.classList.add('tag-item');
      if (currentTag === tag) {
        tagItem.classList.add('active');
      }
      tagItem.dataset.tag = tag;
      tagItem.innerHTML = `
        <span>${tag}</span>
        <span class="tag-count">${tagCount}</span>
      `;
      tagList.appendChild(tagItem);
    });

    // 更新当前标签显示
    currentTagName.textContent = currentTag === 'all' ? '全部书签' : currentTag;
  }

  // 渲染书签列表
  function renderBookmarks() {
    bookmarkGrid.innerHTML = '';

    // 过滤书签
    let filteredBookmarks = bookmarks;

    // 按标签过滤
    if (currentTag !== 'all') {
      filteredBookmarks = filteredBookmarks.filter(bookmark => 
        bookmark.tags.includes(currentTag)
      );
    }

    // 按搜索关键词过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filteredBookmarks = filteredBookmarks.filter(bookmark => 
        bookmark.title.toLowerCase().includes(query) ||
        bookmark.url.toLowerCase().includes(query) ||
        bookmark.tags.some(tag => tag.toLowerCase().includes(query))
      );
    }

    // 排序书签
    const sortMethod = sortSelect.value;
    filteredBookmarks.sort((a, b) => {
      switch (sortMethod) {
        case 'title-asc':
          return a.title.localeCompare(b.title);
        case 'title-desc':
          return b.title.localeCompare(a.title);
        case 'date-asc':
          return new Date(a.createdAt) - new Date(b.createdAt);
        case 'date-desc':
          return new Date(b.createdAt) - new Date(a.createdAt);
        default:
          return 0;
      }
    });

    // 渲染空状态
    if (filteredBookmarks.length === 0) {
      const emptyState = document.createElement('div');
      emptyState.classList.add('empty-state');
      emptyState.innerHTML = `
        <p>暂无书签</p>
        <small>添加一些书签来开始使用吧！</small>
      `;
      bookmarkGrid.appendChild(emptyState);
      return;
    }

    // 渲染书签卡片
    filteredBookmarks.forEach(bookmark => {
      const bookmarkCard = document.createElement('div');
      bookmarkCard.classList.add('bookmark-card');
      bookmarkCard.dataset.id = bookmark.id;
      
      // 如果书签被选中，添加选中样式
      if (selectedBookmarks.has(bookmark.id)) {
        bookmarkCard.classList.add('selected');
      }

      // 生成标签HTML
      const tagsHTML = bookmark.tags.map(tag => 
        `<span class="bookmark-card-tag">${tag}</span>`
      ).join('');

      bookmarkCard.innerHTML = `
        <h3>${bookmark.title}</h3>
        <a href="${bookmark.url}" class="bookmark-url" target="_blank">${truncateUrl(bookmark.url)}</a>
        <div class="bookmark-card-tags">
          ${tagsHTML}
        </div>
        <div class="bookmark-card-actions">
          <button class="bookmark-edit-btn">编辑</button>
          <button class="bookmark-delete-btn">删除</button>
        </div>
      `;

      bookmarkGrid.appendChild(bookmarkCard);
    });
  }

  // 处理添加书签
  function handleAddBookmark() {
    const title = titleInput.value.trim();
    let url = urlInput.value.trim();
    const tagsInputValue = tagsInput.value.trim();

    // 验证输入
    if (!title || !url) {
      alert('请输入标题和URL');
      return;
    }

    // 确保URL有协议
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'https://' + url;
    }

    // 解析标签
    const newTags = tagsInputValue ? tagsInputValue.split(',').map(tag => tag.trim()) : [];

    // 创建新书签
    const newBookmark = {
      id: Date.now(),
      title,
      url,
      tags: newTags,
      createdAt: new Date().toISOString()
    };

    // 添加到书签列表
    bookmarks.push(newBookmark);
    saveBookmarks();
    extractTags();

    // 清空输入框
    titleInput.value = '';
    urlInput.value = '';
    tagsInput.value = '';

    // 更新视图
    renderTags();
    renderBookmarks();
  }

  // 处理标签点击
  function handleTagClick(e) {
    const tagItem = e.target.closest('.tag-item');
    if (!tagItem) return;

    currentTag = tagItem.dataset.tag;
    renderTags();
    renderBookmarks();
  }
  
  // 设置标签右键菜单
  function setupTagContextMenu() {
    // 全局右键菜单处理
    document.addEventListener('contextmenu', function(e) {
      if (e.target.closest('.tag-item')) {
        e.preventDefault();
      }
    });
    
    // 标签右键删除
    tagList.addEventListener('contextmenu', function(e) {
      const tagItem = e.target.closest('.tag-item');
      if (!tagItem || tagItem.dataset.tag === 'all') return;
      
      e.preventDefault();
      
      if (confirm(`确定要删除标签 "${tagItem.dataset.tag}" 吗？\n注意：相关书签不会被删除，但该标签将从书签中移除。`)) {
        const tagToDelete = tagItem.dataset.tag;
        
        // 从所有书签中移除该标签
        bookmarks.forEach(bookmark => {
          bookmark.tags = bookmark.tags.filter(tag => tag !== tagToDelete);
        });
        
        saveBookmarks();
        extractTags();
        renderTags();
        renderBookmarks();
      }
    });
  }
  
  // 处理书签操作（编辑/删除/选择）
  function handleBookmarkAction(e) {
    const actionButton = e.target;
    const bookmarkCard = actionButton.closest('.bookmark-card');
    if (!bookmarkCard) return;

    const bookmarkId = parseInt(bookmarkCard.dataset.id);

    // 处理编辑
    if (actionButton.classList.contains('bookmark-edit-btn')) {
      handleEditBookmark(bookmarkId);
    }
    // 处理删除
    else if (actionButton.classList.contains('bookmark-delete-btn')) {
      handleDeleteBookmark(bookmarkId);
    }
    // 处理卡片点击（用于批量选择）
    else if (!actionButton.closest('.bookmark-card-actions')) {
      toggleBookmarkSelection(bookmarkId, bookmarkCard);
    }
  }
  
  // 切换书签选择状态
  function toggleBookmarkSelection(id, card) {
    if (selectedBookmarks.has(id)) {
      selectedBookmarks.delete(id);
      card.classList.remove('selected');
    } else {
      selectedBookmarks.add(id);
      card.classList.add('selected');
    }
    
    updateBatchActions();
  }
  
  // 更新批量操作栏
  function updateBatchActions() {
    const batchActions = document.querySelector('.batch-actions');
    const selectedCount = document.getElementById('selected-count');
    
    if (selectedBookmarks.size > 0) {
      batchActions.style.display = 'flex';
      selectedCount.textContent = `已选择 ${selectedBookmarks.size} 个书签`;
    } else {
      batchActions.style.display = 'none';
    }
  }
  
  // 批量删除书签
  function handleBatchDelete() {
    if (confirm(`确定要删除选中的 ${selectedBookmarks.size} 个书签吗？`)) {
      bookmarks = bookmarks.filter(bookmark => !selectedBookmarks.has(bookmark.id));
      saveBookmarks();
      extractTags();
      
      // 清空选择状态
      selectedBookmarks.clear();
      updateBatchActions();
      
      renderTags();
      renderBookmarks();
    }
  }
  
  // 取消选择
  function cancelSelection() {
    selectedBookmarks.clear();
    updateBatchActions();
    renderBookmarks();
  }
  
  // 处理键盘快捷键
  function handleKeyPress(e) {
    // Ctrl/Cmd + A 全选
    if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
      e.preventDefault();
      selectAllBookmarks();
    }
    
    // Delete 键删除选中项
    if (e.key === 'Delete' && selectedBookmarks.size > 0) {
      handleBatchDelete();
    }
    
    // Escape 键取消选择
    if (e.key === 'Escape' && selectedBookmarks.size > 0) {
      cancelSelection();
    }
  }
  
  // 全选书签
  function selectAllBookmarks() {
    // 获取当前筛选后的书签
    let filteredBookmarks = bookmarks;
    if (currentTag !== 'all') {
      filteredBookmarks = filteredBookmarks.filter(bookmark => 
        bookmark.tags.includes(currentTag)
      );
    }
    
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filteredBookmarks = filteredBookmarks.filter(bookmark => 
        bookmark.title.toLowerCase().includes(query) ||
        bookmark.url.toLowerCase().includes(query) ||
        bookmark.tags.some(tag => tag.toLowerCase().includes(query))
      );
    }
    
    // 全选或取消全选
    if (selectedBookmarks.size === filteredBookmarks.length) {
      // 取消全选
      selectedBookmarks.clear();
    } else {
      // 全选
      selectedBookmarks = new Set(filteredBookmarks.map(bookmark => bookmark.id));
    }
    
    updateBatchActions();
    renderBookmarks();
  }
  
  // 防抖函数
  function debounce(func, wait) {
    let timeout;
    return function() {
      const context = this;
      const args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(context, args), wait);
    };
  }

  // 处理编辑书签
  function handleEditBookmark(id) {
    const bookmark = bookmarks.find(b => b.id === id);
    if (!bookmark) return;

    // 填充编辑表单
    editingBookmarkId = id;
    editTitleInput.value = bookmark.title;
    editUrlInput.value = bookmark.url;
    editTagsInput.value = bookmark.tags.join(', ');

    // 显示模态框
    editModal.style.display = 'flex';
  }

  // 处理保存编辑
  function handleSaveEdit() {
    const title = editTitleInput.value.trim();
    let url = editUrlInput.value.trim();
    const tagsInputValue = editTagsInput.value.trim();

    // 验证输入
    if (!title || !url) {
      alert('请输入标题和URL');
      return;
    }

    // 确保URL有协议
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'https://' + url;
    }

    // 解析标签
    const newTags = tagsInputValue ? tagsInputValue.split(',').map(tag => tag.trim()) : [];

    // 更新书签
    const bookmarkIndex = bookmarks.findIndex(b => b.id === editingBookmarkId);
    if (bookmarkIndex !== -1) {
      bookmarks[bookmarkIndex] = {
        ...bookmarks[bookmarkIndex],
        title,
        url,
        tags: newTags
      };

      saveBookmarks();
      extractTags();
      closeModal();
      renderTags();
      renderBookmarks();
    }
  }

  // 处理删除书签
  function handleDeleteBookmark(id) {
    if (confirm('确定要删除这个书签吗？')) {
      bookmarks = bookmarks.filter(bookmark => bookmark.id !== id);
      saveBookmarks();
      extractTags();
      renderTags();
      renderBookmarks();
    }
  }

  // 关闭模态框
  function closeModal() {
    editModal.style.display = 'none';
    editingBookmarkId = null;
    editTitleInput.value = '';
    editUrlInput.value = '';
    editTagsInput.value = '';
  }

  // 处理搜索
  function handleSearch() {
    searchQuery = searchInput.value.trim().toLowerCase();
    renderBookmarks();
  }

  // 处理标签点击
  function handleTagClick(e) {
    const tagItem = e.target.closest('.tag-item');
    if (!tagItem) return;

    currentTag = tagItem.dataset.tag;
    renderTags();
    renderBookmarks();
  }

  // 处理添加标签
  function handleAddTag() {
    const newTag = prompt('请输入新标签名称：');
    if (newTag && newTag.trim()) {
      const trimmedTag = newTag.trim();
      if (!tags.includes(trimmedTag)) {
        // 创建一个示例书签来保存新标签
        const exampleBookmark = {
          id: Date.now(),
          title: '示例书签',
          url: 'https://example.com',
          tags: [trimmedTag],
          createdAt: new Date().toISOString()
        };
        bookmarks.push(exampleBookmark);
        saveBookmarks();
        extractTags();
        renderTags();
        renderBookmarks();
      } else {
        alert('该标签已存在');
      }
    }
  }

  // 处理导出
  function handleExport() {
    const dataStr = JSON.stringify(bookmarks, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);

    const exportFileDefaultName = `bookmarks_export_${new Date().toISOString().split('T')[0]}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  }

  // 处理导入
  function handleImport(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function(event) {
      try {
        const importedBookmarks = JSON.parse(event.target.result);
        
        // 验证导入数据格式
        if (!Array.isArray(importedBookmarks)) {
          throw new Error('导入数据格式不正确');
        }

        // 合并书签并去重
        const existingIds = new Set(bookmarks.map(b => b.id));
        const newBookmarks = importedBookmarks.filter(b => 
          !existingIds.has(b.id) && b.title && b.url
        );

        bookmarks = [...bookmarks, ...newBookmarks];
        saveBookmarks();
        extractTags();
        renderTags();
        renderBookmarks();

        alert(`成功导入 ${newBookmarks.length} 个书签`);
      } catch (error) {
        alert('导入失败：' + error.message);
      }
      
      // 重置文件输入
      importInput.value = '';
    };
    reader.readAsText(file);
  }

  // 辅助函数：截断URL
  function truncateUrl(url) {
    // 移除协议部分
    let displayUrl = url.replace(/^https?:\/\//, '');
    // 移除末尾的斜杠
    if (displayUrl.endsWith('/')) {
      displayUrl = displayUrl.slice(0, -1);
    }
    // 截断过长的URL
    if (displayUrl.length > 60) {
      displayUrl = displayUrl.substring(0, 57) + '...';
    }
    return displayUrl;
  }
  
  // 尝试获取当前浏览器标签页信息（用于自动填充）
  function tryGetCurrentTabInfo() {
    try {
      // 检查是否在扩展环境中
      if (typeof chrome !== 'undefined' && chrome.tabs) {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          if (tabs && tabs[0] && !titleInput.value && !urlInput.value) {
            titleInput.value = tabs[0].title || '';
            urlInput.value = tabs[0].url || '';
          }
        });
      }
    } catch (error) {
      // 如果在普通网页中运行，忽略错误
      console.log('无法获取浏览器标签页信息:', error);
    }
  }

  // 启动应用
  init();
  
  // 尝试自动填充当前标签页信息
  tryGetCurrentTabInfo();
});